package com.fanml.service;

import com.fanml.entty.constant.ConstantValue;
import com.fanml.entty.netty.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.util.CharsetUtil;

/**
 * @title: MsgEncoder
 * @Author fanml
 * @describe: //TODO
 * @Date: 2021/7/4 16:28
 * @Version 1.0
 */

public class MsgEncoder extends MessageToByteEncoder<Message> {
    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Message message, ByteBuf byteBuf) throws Exception {

        byteBuf.writeInt(ConstantValue.MSG_HEAD);
        byteBuf.writeInt(message.getSessionId().length());
        byteBuf.writeCharSequence(message.getSessionId(), CharsetUtil.UTF_8);
        byteBuf.writeInt(message.getMsgTypeEnum().getType());
        if (message.getMsgBody() == null) {
            byteBuf.writeInt(0);
        } else {
            byteBuf.writeInt(message.getMsgLength());
            byteBuf.writeBytes(message.getMsgBody());
        }
    }
}
